/**
 * 头脑风暴启动模式对话框
 * 支持3种启动模式：从热点启动、从模板启动、从空白启动
 */
import React, { useState, useEffect } from 'react';
import { Modal, Card, Input, Button, Space, List, Tag, Radio, Select, Spin } from 'antd';
import {
  ThunderboltOutlined,
  FileTextOutlined,
  EditOutlined,
  ClockCircleOutlined,
  RobotOutlined,
} from '@ant-design/icons';
import { useBrainstormStore } from '@/stores/brainstorm.store';
import { brainstormService } from '@/services/brainstorm.service';
import modelConfigService from '@/services/model-config.service';
import type { CreationSession } from '@/types/brainstorm';
import type { ModelConfigInfo } from '@/types/model-config';
import './style.css';

export interface StartupModalProps {
  open: boolean;
  onClose: () => void;
  onStart: (sessionId: string) => void;
  defaultMode?: 'hot' | 'template' | 'blank';
  hotTopicId?: string;
  hotTopicTitle?: string;
}

type StartMode = 'hot' | 'template' | 'blank';

export const StartupModal: React.FC<StartupModalProps> = ({
  open,
  onClose,
  onStart,
  defaultMode = 'blank',
  hotTopicId,
  hotTopicTitle,
}) => {
  const { sessions, createSession } = useBrainstormStore();
  const [mode, setMode] = useState<StartMode>(defaultMode);
  const [topic, setTopic] = useState('');
  const [goal, setGoal] = useState('');
  const [selectedModelId, setSelectedModelId] = useState<string | undefined>();
  const [availableModels, setAvailableModels] = useState<ModelConfigInfo[]>([]);
  const [loadingModels, setLoadingModels] = useState(false);
  const [loading, setLoading] = useState(false);

  // 从热点启动时自动填充主题
  useEffect(() => {
    if (mode === 'hot' && hotTopicTitle) {
      setTopic(hotTopicTitle);
    }
  }, [mode, hotTopicTitle]);

  // 加载可用的AI模型
  useEffect(() => {
    if (open) {
      loadAvailableModels();
    }
  }, [open]);

  const loadAvailableModels = async () => {
    setLoadingModels(true);
    try {
      const models = await modelConfigService.getAvailableModels();
      setAvailableModels(models);
      // 默认选择第一个可用模型
      if (models.length > 0 && !selectedModelId) {
        setSelectedModelId(models[0].id);
      }
    } catch (error) {
      console.error('Failed to load models:', error);
    } finally {
      setLoadingModels(false);
    }
  };

  // 获取最近的3个会话
  const recentSessions = sessions.slice(0, 3);

  const handleStart = async () => {
    if (!topic.trim()) {
      return;
    }

    setLoading(true);
    try {
      // 创建新会话
      const session = await brainstormService.createSession({
        topic: topic.trim(),
        hotTopicId: mode === 'hot' ? hotTopicId : undefined,
        templateId: mode === 'template' ? undefined : undefined, // TODO: 待7.1.9实现
        modelId: selectedModelId, // 传递选中的模型ID
      });

      // 生成引导问题，传入主题和模型ID以便生成动态提示
      const questions = await brainstormService.generateQuestions(
        session.id,
        5, // 生成5个问题
        topic.trim(), // 传入主题
        selectedModelId // 传递模型ID
      );

      // 更新Store - 包含问题
      createSession(topic.trim(), hotTopicId, undefined);

      // 将问题添加到新创建的会话中
      const { updateSession } = useBrainstormStore.getState();
      updateSession({ questions });

      onStart(session.id);
    } catch (error) {
      console.error('Failed to start session:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleContinueSession = (session: CreationSession) => {
    onStart(session.id);
  };

  const modeCards = [
    {
      key: 'hot' as StartMode,
      title: '从热点启动',
      icon: <ThunderboltOutlined style={{ fontSize: 32, color: '#ff4d4f' }} />,
      description: '基于热点话题快速开启创作',
      disabled: !hotTopicId,
    },
    {
      key: 'template' as StartMode,
      title: '从模板启动',
      icon: <FileTextOutlined style={{ fontSize: 32, color: '#1890ff' }} />,
      description: '使用已有模板快速开始（待实现）',
      disabled: true, // 待7.1.9实现
    },
    {
      key: 'blank' as StartMode,
      title: '从空白启动',
      icon: <EditOutlined style={{ fontSize: 32, color: '#52c41a' }} />,
      description: '完全自由发挥，输入任意主题',
      disabled: false,
    },
  ];

  return (
    <Modal
      title="开始新的创作"
      open={open}
      onCancel={onClose}
      footer={null}
      width={800}
      className="startup-modal"
    >
      <div className="startup-modal-content">
        {/* 模式选择 */}
        <div className="mode-selection">
          <h3>选择启动模式</h3>
          <Space size={16}>
            {modeCards.map((card) => (
              <Card
                key={card.key}
                hoverable={!card.disabled}
                className={`mode-card ${mode === card.key ? 'active' : ''} ${card.disabled ? 'disabled' : ''}`}
                onClick={() => !card.disabled && setMode(card.key)}
              >
                <div className="mode-icon">{card.icon}</div>
                <div className="mode-title">{card.title}</div>
                <div className="mode-description">{card.description}</div>
                {card.disabled && <Tag color="orange">即将推出</Tag>}
              </Card>
            ))}
          </Space>
        </div>

        {/* 主题输入 */}
        <div className="topic-input-section">
          <h3>创作主题</h3>
          <Input
            size="large"
            placeholder="请输入你的创作主题..."
            value={topic}
            onChange={(e) => setTopic(e.target.value)}
            disabled={mode === 'hot' && !!hotTopicTitle}
            maxLength={100}
            showCount
          />
          {mode === 'hot' && hotTopicTitle && (
            <div className="hot-topic-hint">
              💡 已自动填充热点标题，你可以修改
            </div>
          )}
        </div>

        {/* AI模型选择 */}
        <div className="model-selection-section">
          <h3>
            <RobotOutlined /> AI助手选择
          </h3>
          <Select
            size="large"
            style={{ width: '100%' }}
            placeholder="选择AI模型来生成提示"
            value={selectedModelId}
            onChange={setSelectedModelId}
            loading={loadingModels}
            notFoundContent={loadingModels ? <Spin size="small" /> : '暂无可用模型'}
          >
            {availableModels.map((model) => (
              <Select.Option key={model.id} value={model.id}>
                <Space>
                  <span>{model.name}</span>
                  {model.status === 'healthy' && <Tag color="success">在线</Tag>}
                  {model.provider && <Tag>{model.provider}</Tag>}
                </Space>
              </Select.Option>
            ))}
          </Select>
          <div className="model-hint">
            💡 选择不同的AI模型会影响提示的风格和质量
          </div>
        </div>

        {/* 创作目标（可选） */}
        <div className="goal-input-section">
          <h3>创作目标（可选）</h3>
          <Input.TextArea
            placeholder="简要描述你的创作目标，例如：写一篇技术科普文章..."
            value={goal}
            onChange={(e) => setGoal(e.target.value)}
            rows={3}
            maxLength={200}
            showCount
          />
        </div>

        {/* 最近会话 */}
        {recentSessions.length > 0 && (
          <div className="recent-sessions">
            <h3>
              <ClockCircleOutlined /> 最近的创作
            </h3>
            <List
              dataSource={recentSessions}
              renderItem={(session) => (
                <List.Item
                  className="session-item"
                  onClick={() => handleContinueSession(session)}
                  style={{ cursor: 'pointer' }}
                >
                  <List.Item.Meta
                    title={session.title}
                    description={
                      <Space>
                        <Tag color={session.stage === 'completed' ? 'success' : 'processing'}>
                          {session.stage === 'brainstorming' && '头脑风暴中'}
                          {session.stage === 'writing' && '内容撰写中'}
                          {session.stage === 'optimizing' && '优化中'}
                          {session.stage === 'completed' && '已完成'}
                        </Tag>
                        <span>{new Date(session.updatedAt).toLocaleString()}</span>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </div>
        )}

        {/* 操作按钮 */}
        <div className="modal-actions">
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button
              type="primary"
              size="large"
              onClick={handleStart}
              loading={loading}
              disabled={!topic.trim()}
            >
              开始创作
            </Button>
          </Space>
        </div>
      </div>
    </Modal>
  );
};
